<?php
declare(strict_types=1);

namespace SixShop\WechatPay\Trait;

use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise\PromiseInterface;
use SixShop\WechatPay\Facade\WechatPayBuilder;
use ErrorException;
use think\facade\Log;

trait HandleAsyncRequestTrait
{
    private function handleAsyncRequest(PromiseInterface|\Closure $promiseOrCallback, ...$args)
    {
        if ($promiseOrCallback instanceof \Closure) {
            $promise = $promiseOrCallback(WechatPayBuilder::getBuilderChainable(), WechatPayBuilder::getConfig(), ...$args);
        } else {
            $promise = $promiseOrCallback;
        }
        return $promise
            ->then(function ($response) {
                Log::info('微信支付异步回调返回数据：' . $response->getBody());
                return json_decode((string)$response->getBody());
            })
            ->otherwise(function ($e) {
                if ($e instanceof RequestException && $e->hasResponse()) {
                    $content = $e->getResponse()->getBody()->getContents();
                    Log::error('微信支付异步回调错误：message={message} content={content}', [
                        'message' => $e->getMessage(),
                        'content' => $content
                    ]);
                    if (json_validate($content)) {
                        $errorBody = json_decode($content);
                        throw new ErrorException(severity: $e->getCode(), message: trim($errorBody->message));
                    }
                }
                throw $e;
            })
            ->wait();
    }
}